package com.khoinguyen.feedtweet.business;

import java.util.ArrayList;
import java.util.List;

import twitter4j.IDs;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

import com.khoinguyen.feedtweet.dao.TwitterConfigurationDao;
import com.khoinguyen.feedtweet.model.TwitterConfig;

public class TwitterBusiness {
	// private static Twitter twitter = new TwitterFactory().getInstance();
	private static Twitter twitter = initTwitterInstance();

	private static Twitter initTwitterInstance() {
		ConfigurationBuilder builder = new ConfigurationBuilder();
		TwitterConfig config = TwitterConfigurationDao.getTwitterConfig();
		if (config == null)
			return null;
		builder.setOAuthConsumerKey(config.getConsumerKey()).setOAuthConsumerSecret(config.getConsumerSecret()).setOAuthAccessToken(config.getAccessToken())
				.setOAuthAccessTokenSecret(config.getAccessTokenSecret()).setDebugEnabled(true);
		TwitterFactory factory = new TwitterFactory(builder.build());
		Twitter twitter = factory.getInstance();
		return twitter;
	}

	public static List<Status> getStatusByUserId(long Id) {
		List<Status> statuses = new ArrayList<Status>();
		List<Status> pagedStatues = new ArrayList<Status>();
		int pageNo = 1;
		do {
			Paging paging = new Paging(pageNo);
			try {
				pagedStatues = twitter.getUserTimeline(Id, paging);
				statuses.addAll(pagedStatues);
			} catch (TwitterException e) {
				e.printStackTrace();
				if (e.getStatusCode() == 429) {
					System.out.println("EXITING....");
					System.exit(0);
				}
			}
			pageNo++;
		} while (pagedStatues.size() > 0);
		return statuses;
	}

	public static List<Long> getFolloweeByName(String name) {
		List<Long> result = new ArrayList<Long>();
		long cursor = -1;
		IDs ids = null;
		try {
			ids = twitter.getFriendsIDs(name, cursor);
		} catch (TwitterException e1) {
			e1.printStackTrace();
		}
		if (ids != null) {
			for (long id : ids.getIDs()) {
				result.add(id);
			}
		}
		return result;
	}
}
